package com.sqfw.project.knowledge.controller;

import com.sqfw.common.utils.SecurityUtils;
import com.sqfw.common.utils.file.FileUtils;
import com.sqfw.common.utils.poi.ExcelUtil;
import com.sqfw.framework.aspectj.lang.annotation.Log;
import com.sqfw.framework.aspectj.lang.enums.BusinessType;
import com.sqfw.framework.config.RuoYiConfig;
import com.sqfw.framework.interceptor.annotation.RepeatSubmit;
import com.sqfw.framework.security.LoginUser;
import com.sqfw.framework.web.controller.BaseController;
import com.sqfw.framework.web.domain.AjaxResult;
import com.sqfw.framework.web.page.TableDataInfo;
import com.sqfw.project.knowledge.domain.KlContentInfo;
import com.sqfw.project.knowledge.domain.query.KlContentInfoQuery;
import com.sqfw.project.knowledge.domain.vo.KlContentInfoCountVo;
import com.sqfw.project.knowledge.domain.vo.KlContentInfoExcel;
import com.sqfw.project.knowledge.domain.vo.KlContentInfoExcelVo;
import com.sqfw.project.knowledge.service.KlContentService;
import com.sqfw.project.system.domain.SysDept;
import com.sqfw.project.system.domain.SysDictData;
import com.sqfw.project.system.service.ISysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 知识库数据，添加，查询，修改，审核
 *
 * @author tangxt
 * */
@Api(tags = "知识库")
@Slf4j
@RequestMapping("/klContent/")
@RestController
public class KlContentController extends BaseController {

    @Autowired
    private KlContentService klContentService;

    @Autowired
    private ISysDeptService deptService;


    /**
     * 查询知识分类
     * @return 返回知识分类
     * */
    @ApiOperation("查询知识分类")
    @PreAuthorize("@ss.hasPermi('getKnowledgeSortList')")
    @GetMapping("getKnowledgeSortList")
    public AjaxResult getKnowledgeSortList() {
        return klContentService.getKnowledgeSortList();
    }


    /**
     * 查询知识形式，知识来源
     * @param type 字典类型
     * @return
     * */
    @ApiOperation("查询知识形式，知识来源")
    @PreAuthorize("@ss.hasPermi('getKnowledgeShapeList')")
    @GetMapping("getKnowledgeShapeList")
    public AjaxResult getKnowledgeShapeList(@RequestParam("type") String type) {
        SysDictData dictData = new SysDictData();
        dictData.setDictType(type);
        List<SysDictData> sysDictDataList = klContentService.getKnowledgeShapeList(dictData);
        if (CollectionUtils.isEmpty(sysDictDataList)) {
            return AjaxResult.error("没有数据");
        }
        return AjaxResult.success(sysDictDataList);
    }

    /**
     * 获取部门树列表（对应知识的：来源:所属组织机构 ---部门id）
     * @param dept
     * @return
     */
    @ApiOperation("获取部门树列表")
    @PreAuthorize("@ss.hasPermi('kl:getDeptList')")
    @GetMapping("/getDeptList")
    public AjaxResult getDeptList(SysDept dept) {
        return success(deptService.selectSysDeptTreeList(dept));
    }

    /**
     * 添加知识数据; 是否案例(1-是；0-不是)
     * @param klContentInfo
     * @return
     * */
    @ApiOperation("添加知识数据")
    @RepeatSubmit
    @Log(title = "添加知识数据", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('addKlContentInfo')")
    @PostMapping("addKlContentInfo")
    public AjaxResult addKlContentInfo(@RequestBody @Valid KlContentInfo klContentInfo) {
        return klContentService.addKlContentInfo(klContentInfo);
    }

    /**
     * 添加案例知识数据
     * @param klContentInfo; 是否案例(1-是；0-不是)
     * @return
     * */
    @ApiOperation("添加案例知识数据")
    @Log(title = "添加案例知识数据", businessType = BusinessType.INSERT)
    @PreAuthorize("@ss.hasPermi('addCaseKlContentInfo')")
    @PostMapping("addCaseKlContentInfo")
    public AjaxResult addCaseKlContentInfo(@RequestBody KlContentInfo klContentInfo) {
        return klContentService.addKlContentInfo(klContentInfo);
    }

    /**
     * 修改知识数据
     * @param klContentInfo
     * @return
     * */
    @ApiOperation("修改知识数据")
    @Log(title = "修改知识数据", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('updateKlContentInfo')")
    @PostMapping("updateKlContentInfo")
    public AjaxResult updateKlContentInfo(@RequestBody KlContentInfo klContentInfo) {
        if (StringUtils.isBlank(klContentInfo.getKlId())) {
            return AjaxResult.error("知识id不能为空");
        }
        return klContentService.updateKlContentInfo(klContentInfo);
    }

    /**
     * 点击审核按钮--锁定该知识数据
     * @param klContentInfo klId id
     * @return
     * */
    @ApiOperation("点击审核按钮--锁定该知识数据")
    @Log(title = "点击审核按钮--锁定该知识数据", businessType = BusinessType.UPDATE)
    @PostMapping("toExamineKlContentInfo")
    public AjaxResult toExamineKlContentInfo(@RequestBody KlContentInfo klContentInfo) {
        return klContentService.toExamineKlContentInfo(klContentInfo);
    }

    /**
     * 点击批量审核按钮--锁定这些知识数据-List
     * @param klContentInfo klIdList
     * @return
     * */
    @ApiOperation("点击批量审核按钮--锁定这些知识数据")
    @Log(title = "点击批量审核按钮--锁定这些知识数据", businessType = BusinessType.UPDATE)
    @PostMapping("toExamineKlContentInfoList")
    public AjaxResult toExamineKlContentInfoList(@RequestBody KlContentInfo klContentInfo) {
        return klContentService.toExamineKlContentInfoList(klContentInfo);
    }

    /**
     * 审核确定按钮
     * @param klContentInfo klId, klContentStatus
     * @return
     * */
    @ApiOperation("审核确定按钮")
    @Log(title = "审核确定按钮", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('toExamineDetermine')")
    @PostMapping("toExamineDetermine")
    public AjaxResult toExamineDetermine(@RequestBody KlContentInfo klContentInfo) {
        if (StringUtils.isBlank(klContentInfo.getKlId())) {
            return AjaxResult.error();
        }
        return klContentService.toExamineDetermine(klContentInfo);
    }

    /**
     * 批量审核确定按钮
     * @param klContentInfo klId, klContentStatus
     * @return
     * */
    @ApiOperation("批量审核确定按钮")
    @Log(title = "批量审核确定按钮", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('toExamineDetermineList')")
    @PostMapping("toExamineDetermineList")
    public AjaxResult toExamineDetermineList(@RequestBody KlContentInfo klContentInfo) {
        return klContentService.toExamineDetermineList(klContentInfo);
    }

    /**
     * 在审核页面，点击返回按钮，解除该知识的锁定
     * @param klContentInfo klid 知识id
     * @return
     * */
    @ApiOperation("解除知识锁定")
    @Log(title = "解除知识锁定", businessType = BusinessType.UPDATE)
    @PostMapping("unlockKlContentInfo")
    public AjaxResult unlockKlContentInfo(@RequestBody KlContentInfo klContentInfo) {
        return klContentService.unlockKlContentInfo(klContentInfo);
    }

    /**
     * 批量解锁知识
     * @param klContentInfo klidList 知识idList
     * @return
     * */
    @ApiOperation("批量解锁知识")
    @Log(title = "批量解锁知识", businessType = BusinessType.UPDATE)
    @PostMapping("unlockKlContentInfoList")
    public AjaxResult unlockKlContentInfoList(@RequestBody KlContentInfo klContentInfo) {
        return klContentService.unlockKlContentInfoList(klContentInfo);
    }

    /**
     * 分页查询知识
     * @param klContentInfo 有模糊查询
     * @return
     * */
    @ApiOperation("分页查询知识")
    @PreAuthorize("@ss.hasPermi('queryKlContentInfoList')")
    @GetMapping("queryKlContentInfoList")
    public TableDataInfo queryKlContentInfoList(KlContentInfo klContentInfo) {
        startPage();
        List<KlContentInfo> list = klContentService.queryKlContentInfoList(klContentInfo);
        return getDataTable(list);
    }

    /**
     * 分页查询我的知识案例
     * @param klContentInfo 有模糊查询 isCase：1--是知识案例
     * @return
     * */
    @ApiOperation("分页查询我的知识案例")
    @PreAuthorize("@ss.hasPermi('queryMyKlContentInfoList')")
    @GetMapping("queryMyKlContentInfoList")
    public TableDataInfo queryMyKlContentInfoList(KlContentInfo klContentInfo) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            TableDataInfo tableDataInfo = new TableDataInfo();
            tableDataInfo.setCode(500);
            tableDataInfo.setMsg("获取用户信息失败！");
            return tableDataInfo;
        }
        klContentInfo.setKlContentCreater(loginUser.getUserId().toString());
        klContentInfo.setIsMyCase(true);
        startPage();
        List<KlContentInfo> list = klContentService.queryKlContentInfoList(klContentInfo);
        return getDataTable(list);
    }

    /**
     * 导出我的知识案例
     * @param response
     * @param klContentInfo 搜索的条件
     * */
    @ApiOperation("导出我的知识案例")
    @Log(title = "导出我的知识案例", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('exportMyKlContentInfoList')")
    @PostMapping("exportMyKlContentInfoList")
    public void exportMyKlContentInfoList(HttpServletResponse response, KlContentInfo klContentInfo) {
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        klContentInfo.setKlContentCreater(loginUser.getUserId().toString());
        klContentInfo.setIsMyCase(true);
        List<KlContentInfo> list = klContentService.queryKlContentInfoList(klContentInfo);
        List<KlContentInfoExcelVo> excelVos = new ArrayList<>(list.size() + 16);
        for (KlContentInfo info : list) {
            KlContentInfoExcelVo excelVo = new KlContentInfoExcelVo();
            BeanUtils.copyProperties(info, excelVo);
            excelVos.add(excelVo);
        }
        ExcelUtil<KlContentInfoExcelVo> util = new ExcelUtil<>(KlContentInfoExcelVo.class);
        util.exportExcel(response, excelVos, "知识案例数据");
    }

    /**
     * 物理删除知识案例
     * */
    @ApiOperation("物理删除知识案例")
    @Log(title = "物理删除知识案例", businessType = BusinessType.DELETE)
    @PreAuthorize("@ss.hasPermi('kl:deleteByKlId')")
    @PostMapping("deleteByKlId")
    public AjaxResult deleteByKlId(@RequestBody KlContentInfo klContentInfo) {
        if (StringUtils.isBlank(klContentInfo.getKlId())) {
            return AjaxResult.error("klid必传");
        }
        return toAjax(klContentService.deleteByKlId(klContentInfo.getKlId()));
    }
    /**
     * 根据id查询知识数据
     * @param klId 知识表id
     * @return
     * */
    @ApiOperation("根据id查询知识数据")
    @PreAuthorize("@ss.hasPermi('queryKlContentInfoByKlId')")
    @GetMapping("queryKlContentInfoByKlId")
    public AjaxResult queryKlContentInfoByKlId(@RequestParam("klId") String klId){
        KlContentInfo klContentInfo = klContentService.queryKlContentInfoByKlId(klId);
        if (klContentInfo == null) {
            return AjaxResult.error("没有知识数据");
        }
        return AjaxResult.success(klContentInfo);
    }

    //--------------------------------核实

    /**
     * 查询更新周期7天前的知识，审核通过的, 过期的不查询--添加时计算出来，加一个字段：下一次更新开始时间
     * 当前时间 > 发布时间 + 半年 - 7天 ; 查询出来
     * 已失效的不查询
     * @param klContentInfo
     * @return
     * */
    @ApiOperation("查询更新周期7天前的知识")
    @PreAuthorize("@ss.hasPermi('queryUpdateCycleKlContent')")
    @GetMapping("queryUpdateCycleKlContent")
    public TableDataInfo queryUpdateCycleKlContent(KlContentInfo klContentInfo) {
        startPage();
        List<KlContentInfo> list = klContentService.queryUpdateCycleKlContent(klContentInfo);
        return getDataTable(list);
    }

    /**
     * 更新周期时间到了，进行修改（核实--不修改状态，处理--修改知识状态，重新走一遍审核流程）
     * 修改更新周期的时间
     * @param klContentInfo
     * @return
     * */
    @ApiOperation("更新周期时间到了，进行修改")
    @Log(title = "更新周期时间到了，进行修改", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('updateCycleKlContent')")
    @PostMapping("updateCycleKlContent")
    public AjaxResult updateCycleKlContent(@RequestBody KlContentInfo klContentInfo) {
        if (StringUtils.isBlank(klContentInfo.getKlId()) || StringUtils.isBlank(klContentInfo.getClickType())) {
            return AjaxResult.error("知识id/点击类型不能为空");
        }
        return klContentService.updateCycleKlContent(klContentInfo);
    }

    /**
     * 知识库检索接口, 分页查询
     * @param query
     * @return
     * */
    @ApiOperation("知识库检索接口")
    @PreAuthorize("@ss.hasPermi('retrievalKlContentInfo')")
    @GetMapping("retrievalKlContentInfo")
    public TableDataInfo retrievalKlContentInfo(KlContentInfoQuery query) {
        List<KlContentInfo> list = klContentService.retrievalKlContentInfo(query);
        return getDataTable(list);
    }

    /**
     * 加点击量
     * @param klId 知识id
     * @return
     * */
    @ApiOperation("加点击量")
    @Log(title = "加点击量", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('retrievalKlContentInfo')")
    @GetMapping("plusKlContentHits")
    public AjaxResult plusKlContentHits(@RequestParam("klId") String klId) {
        return toAjax(klContentService.plusKlContentHits(klId));
    }

    /**
     * 提交评分
     * @param query 知识id，评分
     * @return
     * */
    @ApiOperation("提交评分")
    @Log(title = "提交评分", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('retrievalKlContentInfo')")
    @PostMapping("submitScore")
    public AjaxResult submitScore(@RequestBody KlContentInfoQuery query) {
        return klContentService.submitScore(query);
    }

    /**
     * 首页查询10审核通过的知识数据展示
     * @param klContentInfo
     * @return
     * */
    @ApiOperation("首页查询10审核通过的知识数据展示")
    @PreAuthorize("@ss.hasPermi('queryHomeKlContentInfoList')")
    @GetMapping("queryHomeKlContentInfoList")
    public TableDataInfo queryHomeKlContentInfoList(KlContentInfo klContentInfo) {
        List<KlContentInfo> list = klContentService.queryHomeKlContentInfoList(klContentInfo);
        return getDataTable(list);
    }

    /**
     * 首页查询10审核通过的知识数据展示--根据修改时间排序
     * @param klContentInfo
     * @return
     * */
    @ApiOperation("首页查询10审核通过的知识数据展示--根据修改时间排序")
    @PreAuthorize("@ss.hasPermi('queryHomeListOrderByUpdateTime')")
    @GetMapping("queryHomeListOrderByUpdateTime")
    public TableDataInfo queryHomeListOrderByUpdateTime(KlContentInfo klContentInfo) {
        List<KlContentInfo> list = klContentService.queryHomeListOrderByUpdateTime(klContentInfo);
        return getDataTable(list);
    }

    /**
     * 首页根据知识分类统计, 目前只统计民政业务下的二级分类
     * @param pid 知识分类中的父id  民政业务id
     * @return
     * */
    @ApiOperation("首页根据知识分类统计")
    @PreAuthorize("@ss.hasPermi('countByKnowledgeSortPid')")
    @GetMapping("countByKnowledgeSortPid")
    public AjaxResult countByKnowledgeSortPid(@RequestParam("pid") String pid) {
        List<KlContentInfoCountVo> list = klContentService.countByKnowledgeSortPid(pid);
        return AjaxResult.success(list);
    }


    /**
     * 知识信息查询列表数据的--导出
     * @param response
     * @param klContentInfo 搜索的条件
     * */
    @ApiOperation("知识信息查询列表数据的--导出")
    @Log(title = "导出知识信息查询列表", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('kl:exportQueryList')")
    @PostMapping("exportQueryList")
    public void exportQueryList(HttpServletResponse response, KlContentInfo klContentInfo) {
        List<KlContentInfo> list = klContentService.queryKlContentInfoList(klContentInfo);
        ExcelUtil<KlContentInfo> util = new ExcelUtil<KlContentInfo>(KlContentInfo.class);
        util.exportExcel(response, list, "知识库数据");
    }

    /**
     * 根据部门分页查询知识数据
     * @param klContentInfo 有模糊查询
     * @return
     * */
    @ApiOperation("根据部门查询知识数据")
    @PreAuthorize("@ss.hasPermi('queryKlContentInfoByDept')")
    @GetMapping("queryKlContentInfoByDept")
    public TableDataInfo queryKlContentInfoByDept(KlContentInfo klContentInfo){
        // 获取当前的用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 部门id
        klContentInfo.setKlContentSources(loginUser.getDeptId().toString());
        startPage();
        List<KlContentInfo> list = klContentService.queryKlContentInfoList(klContentInfo);
        return getDataTable(list);
    }


    /**
     * 下载静态文件---没有使用
     * @param response
     * */
    @GetMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
//        ExcelUtil<KlContentInfo> util = new ExcelUtil<KlContentInfo>(KlContentInfo.class);
//        util.importTemplateExcel(response, "员工导入模板");
        try {

            // 本地资源路径
            String localPath = RuoYiConfig.getProfile();

            //要下载的文件名test.xlsx
            String fileName = "knowledgeInfoModel.xlsx";
            // D:\devMaven\noas-portal\portal-user\file\
            String path = System.getProperty("user.dir") + "/file/" + fileName;
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(path, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(path, response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("下载文件失败", e);

        }

    }

    /**
     * 导入知识库数据
     * @param file 生产文件
     * @return
     * */
    @ApiOperation("导入知识库数据")
    @Log(title = "知识批量导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('kl:importData')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<KlContentInfoExcel> util = new ExcelUtil<KlContentInfoExcel>(KlContentInfoExcel.class);
        List<KlContentInfoExcel> klContentInfoExcels = util.importExcel(file.getInputStream());
        klContentInfoExcels.remove(0);
        return klContentService.importKlContentInfoExcel(klContentInfoExcels);
    }

    /**
     * 下载静态模板
     * @param request
     * @param response
     * */
    @ApiOperation(value = "下载模板", produces = "application/octet-stream")
    @GetMapping("/downloadTemplate")
    public void downloadTemplate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //要下载的文件名test.xlsx
        String fileName = "knowledgeInfoModel.xlsx";
        // D:\devMaven\noas-portal\portal-user\file\
        String path = System.getProperty("user.dir") + "/file/";
        String realPath = request.getSession().getServletContext().getRealPath(path);
        log.info("下载知识模板文件路径url：{}", path +fileName);
        //设置content-disposition响应头控制浏览器以下载的形式打开文件
        File file=new File(path +fileName);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
        //根据路径获取要下载的文件输入流
        InputStream inputStream= null;
        OutputStream out = null;
        try {
            inputStream = new FileInputStream(file);
            out = response.getOutputStream();
            //创建数据缓冲区
            byte[] b=new byte[1024];
            int length;
            //把文件流写到缓冲区里
            while((length=inputStream.read(b))>0){
                out.write(b,0,length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                out.flush();
                out.close();
                inputStream.close();
            }
        }
    }

    /**
     * 下载静态模板
     * @return
     * String fileName = "file.cap";
     * */
    @ApiOperation(value = "下载知识导入模板")
    @GetMapping("/downloadModel")
    public ResponseEntity<Object> downloadModel() throws Exception {
        //要下载的文件名test.xlsx
        String fileName = "knowledgeInfoModel.xlsx";
        // D:\devMaven\noas-portal\portal-user\file\
        String path = System.getProperty("user.dir") + "/file/";
        log.info("下载知识模板文件路径url：{}", path +fileName);
        //设置content-disposition响应头控制浏览器以下载的形式打开文件
        File file=new File(path +fileName);
        if (!file.exists()) {
            throw new NullPointerException("文件路径不存在");
        }
        InputStreamResource resource = null;
        try {
            resource = new InputStreamResource(new FileInputStream(file));
        }catch (Exception e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + fileName);
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        ResponseEntity<Object> responseEntity = ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
        return responseEntity;
    }



    /**
     * 根据知识分类统计知识添加数量，核实数量
     * @param query
     * @return
     * */
    @ApiOperation("统计知识核实数据")
    @PreAuthorize("@ss.hasPermi('countVerifyKlContentInfo')")
    @GetMapping("countVerifyKlContentInfo")
    public AjaxResult countVerifyKlContentInfo(KlContentInfoQuery query) {
        List<KlContentInfoCountVo> list = klContentService.countVerifyKlContentInfo(query);
        return AjaxResult.success(list);
    }

    /**
     * 工单模块：分页查询知识
     * @param klContentInfo 知识标题
     * @return 返回：知识标题，知识内容
     * */
    @ApiOperation("工单模块：分页查询知识")
    @PreAuthorize("@ss.hasPermi('queryWpKlContentInfoList')")
    @GetMapping("queryWpKlContentInfoList")
    public TableDataInfo queryWpKlContentInfoList(KlContentInfo klContentInfo) {
        klContentInfo.setKlContentIsDel("0");
        startPage();
        List<KlContentInfo> list = klContentService.queryWpKlContentInfoList(klContentInfo);
        return getDataTable(list);
    }


    /**
     * 逻辑删除知识库数据
     * */
    @ApiOperation("逻辑删除知识库数据")
    @Log(title = "逻辑删除知识库数据", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('deleteKlContentInfoByKlId')")
    @PostMapping("deleteKlContentInfoByKlId")
    public AjaxResult deleteKlContentInfoByKlId(@RequestBody KlContentInfo klContentInfo) {
        if (StringUtils.isBlank(klContentInfo.getKlId())) {
            return AjaxResult.error("klid必传");
        }
        return toAjax(klContentService.deleteKlContentInfoByKlId(klContentInfo));
    }


    /**
     * 下载静态模板---测试使用
     * @return
     * String fileName = "file.cap";
     * */
    @ApiOperation(value = "下载知识导入模板")
    @GetMapping("/testDownloadModel")
    public ResponseEntity<Object> testDownloadModel(@RequestParam("fileName") String fileName) throws Exception {
        //要下载的文件名test.xlsx
        // D:\devMaven\noas-portal\portal-user\file\
        String path = System.getProperty("user.dir") + "/file/";
        log.info("下载知识模板文件路径url：{}", path +fileName);
        //设置content-disposition响应头控制浏览器以下载的形式打开文件
        File file=new File(path +fileName);
        if (!file.exists()) {
            throw new NullPointerException("文件路径不存在");
        }
        InputStreamResource resource = null;
        try {
            resource = new InputStreamResource(new FileInputStream(file));
        }catch (Exception e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition", "attachment; filename=" + fileName);
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        ResponseEntity<Object> responseEntity = ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
        return responseEntity;
    }

    /**
     * 下载静态模板
     * @param request
     * @param response
     * */
    @ApiOperation(value = "下载模板", produces = "application/octet-stream")
    @GetMapping("/testDownloadTemplate")
    public void testDownloadTemplate(HttpServletRequest request,
                                     HttpServletResponse response,
                                     @RequestParam("fileName") String fileName) throws IOException {
        //要下载的文件名test.xlsx
        // D:\devMaven\noas-portal\portal-user\file\
        String path = System.getProperty("user.dir") + "/file/";
        String realPath = request.getSession().getServletContext().getRealPath(path);
        log.info("下载知识模板文件路径url：{}", path +fileName);
        //设置content-disposition响应头控制浏览器以下载的形式打开文件
        File file=new File(path +fileName);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName, "UTF-8"));
        //根据路径获取要下载的文件输入流
        InputStream inputStream= null;
        OutputStream out = null;
        try {
            inputStream = new FileInputStream(file);
            out = response.getOutputStream();
            //创建数据缓冲区
            byte[] b=new byte[1024];
            int length;
            //把文件流写到缓冲区里
            while((length=inputStream.read(b))>0){
                out.write(b,0,length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                out.flush();
                out.close();
                inputStream.close();
            }
        }
    }


}
